/**
 * 
 */
package com.cnhaimei.vod.logic;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.cnhaimei.base.BaseActivity;
import com.cnhaimei.com.PageManager;
import com.cnhaimei.com.PageManager.PageInfoListener;
import com.cnhaimei.vod.R;
import com.cnhaimei.vod.bean.Room;
import com.cnhaimei.vod.logic.EventsManager.EventsListener;
import com.cnhaimei.vod.net.NetManager;
import com.cnhaimei.vod.util.Const;
import com.cnhaimei.vod.util.Util;
import com.cnhaimei.com.VODLog;

/**
 * 包间选择
 * 
 * @author Jin001.Wu@gmail.com <br>
 * @date 2011-7-6
 * 
 */
public class RoomsActivity extends BaseActivity implements PageInfoListener,
		EventsListener {
	private final static int REQ_CODE_PASCHECK = 2;
	private final static int REQ_CODE_ENTER = 1;
	private final static String TAG = "RoomsActivity";
	private final static int PerPageCount = 9;
	private final static int CHECK_DIALOG = 1;
	private final static long TIME_OUT = 10 * 1000;
	private final static int MSG_TIME_OUT = 1;

	private GridView roomsView;

	LayoutInflater mInflater;

	AdapterEx mAdapterEx;

	boolean isNeting = false;

	View curRoom;

	String[] rooms;

	PageManager pageManager;

	AlertDialog mAlertDialog;

	String room;

	int dcManagerId;
	
	boolean isOutTime;
	
	Room netRoom;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState,false);
		this.setContentView(R.layout.rooms);

		roomsView = (GridView) findViewById(R.id.rooms);
		mInflater = LayoutInflater.from(this);

		// rooms = (String[]) getIntent()
		// .getSerializableExtra(Const.Key.ROOM_LIST);
		// if (rooms == null) {
		// rooms = new String[0];
		// Log.e(TAG, "rooms is empty");
		// }

		// rooms = getIntent().getStringArrayExtra(Const.Key.ROOM_LIST);
		
		int totalPage = 0;
		if (Util.DEMO || Util.TEST) {
			rooms = new String[30]; // TODO test
			for (int i = 0; i < rooms.length; i++) {
				rooms[i] = String.valueOf(i+ 110);
			}
			
//			if (rooms != null) {
//				totalPage = (rooms.length - 1) / PerPageCount + 1;
//			}
		} else {
			 rooms = getIntent().getStringArrayExtra(Const.Key.ROOM_LIST);
		}
		
		if (rooms != null) {
			totalPage = (rooms.length - 1) / PerPageCount + 1;
		}
		
		VODLog.e(TAG, "rooms totalPage: " + totalPage);

		View preView = findViewById(R.id.pre);
		View nextView = findViewById(R.id.next);
		pageManager = new PageManager();// (0, totalPage);
		pageManager.setPageButtonView(preView, nextView, null, null);
		pageManager.setPageInfo(0, totalPage);
		pageManager.setListener(this);

		mAdapterEx = new AdapterEx();
		mAdapterEx.setList(rooms);

		roomsView.setNumColumns(3);
		roomsView.setAdapter(mAdapterEx);
		roomsView.setOnItemClickListener(mAdapterEx);
		roomsView.setCacheColorHint(Color.TRANSPARENT);
		
		ViewGroup.LayoutParams lpLayoutParams = roomsView.getLayoutParams();

		DisplayMetrics dMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
		float xdpi = dMetrics.widthPixels;//dMetrics.xdpi;
		float ydpi = dMetrics.heightPixels;//dMetrics.ydpi;
		lpLayoutParams.width = (int)(xdpi - 100);
		roomsView.setLayoutParams(lpLayoutParams);

//		XVod.G().registerListener(EventsManager.Event.CHCKD_PAS, this);

		// String ip = "10.0.0.26";
		// dcManagerId = NetManager.G().startDCManager(ip);
	}
	
//	void showEmptyRoomsDialog() {
//		AlertDialog.Builder builder = new AlertDialog.Builder(this);
//		builder.setTitle("无包厢信息");
//		builder.setMessage("查询不到包厢信息，请退出重试，或");
//	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQ_CODE_PASCHECK) {
			if (resultCode == RESULT_OK) {
				enter();
			}
		} else if (requestCode == REQ_CODE_ENTER) {
			if (resultCode == RESULT_OK) { 
				RoomsActivity.this.finish();
				Util.exit();
				setResult(RESULT_CANCELED);
			} else { // 断开返回
				NetManager.G().close(NetManager.G().getDCManangerId()); // 事先关闭
			}
		}
	}
	
//	private void sendTimeOutDelay() {
//		myHandler.removeMessages(MSG_TIME_OUT);
//		myHandler.sendEmptyMessageDelayed(MSG_TIME_OUT, TIME_OUT);
//	}


	public void showEditDialog() {
		Intent i = new Intent(Const.Action.RoomChecked);
		i.putExtra(Const.Key.ROOM_KEY, Util.CUR_ROOM);//netRoom);// 
		startActivityForResult(i, REQ_CODE_PASCHECK);
//		mAlertDialog = new AlertDialog.Builder(this).create();
//		EditText pas = new EditText(this);
//		pas.setId(5);
//		pas.setTransformationMethod(PasswordTransformationMethod.getInstance());
//		mAlertDialog.setView(pas);
//		mAlertDialog.setButton(getString(R.string.ok),
//				new DialogInterface.OnClickListener() {
//					public void onClick(DialogInterface dialog, int which) {
//						EditText et = (EditText) mAlertDialog.findViewById(5);
//						String pas = et.getText().toString();
//						mAlertDialog.getButton(AlertDialog.BUTTON1).setEnabled(
//								false);
//						mAlertDialog.getButton(AlertDialog.BUTTON2).setEnabled(
//								false);
//						// TODO
//						if (Util.DEMO) {
//							enter();
//						} else {
//							XVod.G().passwordCheck(pas);
//						}
//					}
//				});
//		mAlertDialog.setButton2(getString(R.string.cancel),
//				(DialogInterface.OnClickListener) null);
//		mAlertDialog.show();
	}

//	public void getRoomIp() {
//		isOutTime = false;
//		sendTimeOutDelay();
//		if (Util.DEMO || Util.TEST) {
//		enter();
////			showEditDialog();
//		} else {
//			XVod.G().registerListener(EventsManager.Event.ROOM_INFO, this);
//			XVod.G().requestRoomInfo(room);
//		}
//	}
	
	

	public void enter() {
		//startActivityForResult(new Intent(Const.Action.RoomMatched), REQ_CODE_ENTER);
		setResult(RESULT_OK);
		finish();
	}

	public class AdapterEx extends BaseAdapter implements OnItemClickListener {
		String[] lst;// = new ArrayList<Room>();

		public void setList(String[] lst) {
			this.lst = lst;
		}

		public int getCount() {
			if (lst == null) {
				return 0;
			}

			int cur = pageManager.getCurrentIndex();
			int cout = cur * PerPageCount + PerPageCount;
			if (cout > lst.length) {
				return lst.length - cur * PerPageCount;
			} else {
				return PerPageCount;
			}
		}

		public Object getItem(int position) {
			int cur = pageManager.getCurrentIndex();
			return lst == null ? null : lst[cur * PerPageCount + position];
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.rooms_item, null);
				holder = new ViewHolder();
				holder.initView(convertView);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.setValues((String) getItem(position));

			return convertView;
		}

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			if (isNeting) {
				return;
			}

//			if (view == curRoom) {
//			} else {
			if (curRoom != null) {
				curRoom.setBackgroundResource(R.drawable.room_item_unchecked);
				TextView v = ((ViewHolder) view.getTag()).item;
				v.setCompoundDrawablesWithIntrinsicBounds(
						R.drawable.room_item_icon_unckeked, 0, 0, 0);
			}
			curRoom = view;
			curRoom.setBackgroundResource(R.drawable.room_item_checked);
			TextView v = ((ViewHolder) curRoom.getTag()).item;
			v.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.room_item_icon_checked, 0, 0, 0);
			room = v.getText().toString();
			Util.CUR_ROOM = room;
//			getRoomIp();
			showEditDialog();

//			}
			// String r = (String) getItem(position);
			// if (r != null && "108".equals(r)) {
			// showEditDialog();
			// startActivity(Const.Action.RoomMatched);
			// finish();
			// }

		}
	}

	class ViewHolder {

		public TextView item;

		public ViewHolder() {
		}

		public void initView(View layout) {
			item = (TextView) layout.findViewById(R.id.item);
		}

		public void setValues(String data) {
			if (data == null) {
				return;
			}
			item.setText(data);
		}
	}

	public void onPageIndexChanged(int prePageIndex, int currentPageIndex,
			int totalPages) {
		// TODO Auto-generated method stub
		if (curRoom != null) {
			curRoom.setBackgroundResource(R.drawable.room_item_unchecked);
			TextView v = ((ViewHolder) curRoom.getTag()).item;
			v.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.room_item_icon_unckeked, 0, 0, 0);
		}
		curRoom = null;
		mAdapterEx.notifyDataSetChanged();

	}

	public void onPageIndexChangedError(int prePageIndex, int currentPageIndex,
			int totalPages) {
		// TODO Auto-generated method stub

	}

	public void onEvent(int event, Object obj, boolean isSuc) {
		// 重载使父类为空
		switch (event) {
//		case EventsManager.Event.CHCKD_PAS: {
//			if (isSuc) {
//				XVod
//						.G()
//						.unRegisterListener(EventsManager.Event.CHCKD_PAS, this);
//				enter();
//			} else {
//				mAlertDialog.getButton(AlertDialog.BUTTON1).setEnabled(true);
//				mAlertDialog.getButton(AlertDialog.BUTTON2).setEnabled(true);
//				Toast
//						.makeText(this, R.string.password_wrong,
//								Toast.LENGTH_LONG);
//			}
//		}
//			break;
//		case EventsManager.Event.ROOM_INFO: {
//			if (isSuc && obj instanceof Room) {
//				if (!isOutTime) {
//					Room r = (Room) obj;
//					if (r.getNum().equals(room)) {
//						XVod.G().unRegisterListener(
//								EventsManager.Event.ROOM_INFO, this);
////						XVod.G().registerListener(
////								EventsManager.Event.CONNECTING, this);
//						Log.e("RoomsActivity", "" + r.getIp());
//						myHandler.removeMessages(MSG_TIME_OUT);
//						netRoom = r;
//						showEditDialog();
//					}
//				}
//			} else {
//				myHandler.removeMessages(MSG_TIME_OUT);
//				Toast.makeText(this, R.string.get_room_fail, Toast.LENGTH_LONG);
//			}
//		}
//			break;
//		case EventsManager.Event.CONNECTING: {
//			if (obj != null && obj instanceof Integer) {
//				int id = (Integer) obj;
//				if (id == dcManagerId) {
//					XVod.G().unRegisterListener(EventsManager.Event.CONNECTING,
//							this);
//					showEditDialog();
//				}
//			}
//		}
//			break;
		default:
			break;
		}

	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
//			if (Util.TEST || Util.DEMO) {
//				Util.exit();
//			} else {
				//confirmExit(this);
//			}
			//break;
			NetManager.G().closeAll();
		default:
			return super.onKeyDown(keyCode, event);
		}
		//return true;
	}
	
	public  void confirmExit(Activity active) {
		AlertDialog mAlertDialog = new AlertDialog.Builder(active).create();
		mAlertDialog.setIcon(android.R.drawable.ic_dialog_alert);
		mAlertDialog.setTitle(R.string.confirm_exit_title);
		mAlertDialog.setMessage(active.getString(R.string.confirm_exit));
		mAlertDialog.setButton(active.getString(R.string.yes),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						RoomsActivity.this.finish();
						Util.exit();
					}
				});
		mAlertDialog.setButton2(active.getString(R.string.no),
				(DialogInterface.OnClickListener) null);
		mAlertDialog.show();
	}
	
//	private Handler myHandler = new  Handler() {
//		@Override
//		public void handleMessage(Message msg) {
//			switch (msg.what) {
//			case MSG_TIME_OUT:
//				isOutTime = true;
//				Toast.makeText(RoomsActivity.this, R.string.read_room_error, Toast.LENGTH_SHORT).show();
//				break;
//
//			default:
//				break;
//			}
//		}
//		
//	};

}
